<template>
  <div class="ai-chat">
    <div class="chat-history">
      <div v-for="msg in messages" :key="msg.id" :class="msg.role">
        <span>{{ msg.role === 'user' ? '我' : '客服' }}：</span>{{ msg.content }}
      </div>
    </div>
    <div class="chat-input">
      <input v-model="input" @keyup.enter="send" placeholder="请输入问题..." />
      <button @click="send">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { v4 as uuidv4 } from 'uuid'

const sessionId = localStorage.getItem('ai_session_id') || uuidv4()
localStorage.setItem('ai_session_id', sessionId)

const messages = ref([])
const input = ref('')

const send = async () => {
  if (!input.value.trim()) return
  messages.value.push({ id: Date.now(), role: 'user', content: input.value })
  const userMsg = input.value
  input.value = ''
  let aiReply = ''
  const res = await fetch('/ai/stream-chat?sessionId=' + sessionId, {
    method: 'POST',
    headers: { 'Content-Type': 'text/plain' },
    body: userMsg
  })
  const reader = res.body.getReader()
  let decoder = new TextDecoder()
  let buffer = ''
  while (true) {
    const { done, value } = await reader.read()
    if (done) break
    buffer += decoder.decode(value, { stream: true })
    let lines = buffer.split('\n')
    buffer = lines.pop()
    for (const line of lines) {
      if (line.trim()) {
        try {
          const obj = JSON.parse(line)
          const content = obj.message?.content || ''
          if (content) {
            aiReply += content
            // 实时渲染AI回复
            if (messages.value[messages.value.length - 1]?.role === 'assistant') {
              messages.value[messages.value.length - 1].content = aiReply
            } else {
              messages.value.push({ id: Date.now() + 1, role: 'assistant', content: aiReply })
            }
          }
        } catch (e) { /* 忽略解析错误 */ }
      }
    }
  }
}
</script>

<style scoped>
.ai-chat { width: 350px; border: 1px solid #eee; border-radius: 8px; padding: 12px; background: #fff; }
.chat-history { max-height: 300px; overflow-y: auto; margin-bottom: 8px; }
.user { text-align: right; color: #409EFF; }
.assistant { text-align: left; color: #67C23A; }
.chat-input { display: flex; gap: 8px; }
input { flex: 1; padding: 6px; border-radius: 4px; border: 1px solid #ccc; }
button { padding: 6px 16px; }
</style> 